package com.ks.core.validation;

import com.ks.core.anno.MustIn;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Arrays;

/**
 * @author kingdee
 */
public abstract class AbstractMustInValidator<T> implements ConstraintValidator<MustIn, T> {

    protected String[] constraint;

    @Override
    public void initialize(MustIn constraintAnnotation) {
        this.constraint = constraintAnnotation.value();
    }

    @Override
    public boolean isValid(T value, ConstraintValidatorContext context) {
        if (constraint == null || constraint.length == 0) {
            return true;
        }
        return Arrays.asList(constraint).contains(convertToString(value));
    }

    abstract String convertToString(T value);
}
